package com.topisv.tms.web.stock.movestorage;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.stock.CusStockService;
import com.topisv.tms.web.base.BaseController;

/**
 * 库存移位
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2014-11-21      CC            1.0           Create
 */
@Controller
@RequestMapping(value = "/v2_moveStorage")
public class MoveStorageController extends BaseController {
	@Autowired
	private CusStockService cusStockService;

	@RequestMapping(value = "show")
	public String show(Model model) {
		fillSelectValue(model, null);
		return "stock/movestorage/moveStorage";
	}

	@RequestMapping(value = "query",method=RequestMethod.POST)
	public String query(Model model, 
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "sku") String sku) {
		List<CusStock> cusStocks = cusStockService.loadStock(warehouseCode, customerCode, sku);
		model.addAttribute("cusStocks", cusStocks);
		fillSelectValue(model, customerCode);
		return "stock/movestorage/moveStorage";
	}
	@RequestMapping(value = "move",method=RequestMethod.POST)
	@ResponseBody
	public void move(@RequestBody CusStock[] cusStocks, HttpServletResponse response){
	    JSONObject json = null;
        PrintWriter out = null;
        String msg = null;
	    try{
	        json = new JSONObject();
            out = response.getWriter();
	    
    	    CusStock from = null;
    		CusStock to = null;
    		for (CusStock cusStock : cusStocks) {
    			if("from".equals(cusStock.getMoveFlg())){
    				from = cusStock;
    			}else{
    				to = cusStock;
    			}
    		}
    		msg = cusStockService.move(from, to);
    		if(msg == "true"){
                json.put("content", "操作成功"); 
    		}else{
    		    json.put("content", "操作失败");
    		}
	    }catch(PaiUException e){
	        json.put("content", "SKU、批次、生产日期、过期日期不匹配.");
	    }catch(Exception ex){
	        json.put("content",ex.getMessage());
	    }finally{
	        out.print(json.toString());
	    }
	}
}
